package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.dto.DishDto;
import com.itheima.entity.Dish;
import com.itheima.entity.DishFlavor;
import com.itheima.mapper.DishMapper;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 菜品管理 服务实现类
 * </p>
 *
 * @author fengzhu
 * @since 2024-10-10
 */
@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;
    @Override
    public DishDto getByIdWithFlavor(Long id) {
        //查询菜品基本信息和当前菜品对象的口味信息
       Dish dish =  this.getById(id);

       DishDto dishDto = new DishDto();

       //将dish对象拷贝到dishdto里面
       BeanUtils.copyProperties(dish,dishDto);

       //从dish_flavor里面查口味
       LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
       queryWrapper.eq(DishFlavor::getDishId, dish.getId());
       List<DishFlavor> list = dishFlavorService.list(queryWrapper);
       dishDto.setFlavors(list);

       return dishDto;
    }

    @Override
    public void UpdateByStatusByIds(int status, List<Long> ids) {
        LambdaUpdateWrapper<Dish> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.in(Dish::getId,ids)
                    .set(Dish::getStatus,status);
        dishMapper.update(null, queryWrapper);
    }

    @Override
    public void updateWithFlavor(DishDto dishDto,Long empid) {
        //更新dish表
        this.updateById(dishDto);

        Dish dish = new Dish();
        //先清理当前菜品的口味
        LambdaQueryWrapper<DishFlavor> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(DishFlavor::getDishId,dishDto.getId());
        dishFlavorService.remove(updateWrapper);

        List<DishFlavor> dishFlavors = dishDto.getFlavors();
        dishFlavors =dishFlavors.stream().map((item)->{
            item.setDishId(dishDto.getId());
            item.setUpdateUser(empid);
            item.setCreateUser(empid);
            return item;
        }).toList();
        dishFlavorService.saveBatch(dishFlavors);
        //添加当前菜品的口口味
    }
}
